package jplat.tools.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import jplat.tools.config.JBusConfig;

/**
  * Title: FTPUtil 
 * Description: FTP操作的工具类，通过此类可以完成文件到指定FTP服务器的上传和下载。
  * @version 1.0  
  */
@Service
public class FtpTool
{
	private Logger logger = Logger.getLogger(FtpTool.class);
	private static ChannelSftp sftp = null;
	
	private static Session session = null;

	 /** 
     * FTP上传单个文件测试 
     * @param file 本地文件
     * @param workDir 上传服务器文件的目录
     * @param fileName 上传到服务器的文件名称
	 * @throws Exception 
     */ 
    public static void ftpUpload(File file,String workDir,String fileName) throws Exception { 
        FTPClient ftpClient = new FTPClient(); 
        FileInputStream fis = null; 

        try { 
	        ftpClient.connect(JBusConfig.FTP_IP); 
            ftpClient.login(JBusConfig.FTP_USER,JBusConfig.FTP_PWD); 
	        fis = new FileInputStream(file); 
 	     
            //设置上传目录 
            ftpClient.changeWorkingDirectory(JBusConfig.FTP_PATH); 
            ftpClient.setBufferSize(1024); 
            ftpClient.setControlEncoding("GBK"); 
            //设置文件类型（二进制） 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftpClient.storeFile(fileName, fis); 
        } catch (IOException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("FTP客户端出错！", e); 
        } finally { 
            IOUtils.closeQuietly(fis); 
            try { 
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("关闭FTP连接发生异常！", e); 
            } 
        } 
    } 
    /**
     * 转码 (FTP协议里面，规定文件名编码为iso-8859-1，所以只能建转码以后的目录和文件)
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String transcoding(String str) throws UnsupportedEncodingException {
        return new String(str.getBytes("GBK"),"iso-8859-1");
    }
	/**
	 * 从ftp下载文件
	 * 
	 * @param FtpFileName
	 *          ftp文件名称
	 * @param LocaFileName
	 *          目的文件名称
	 * @return boolean true表示下载文件成功，false表示下载文件失败
	 * @throws Exception
	 */
	public static boolean doDownFile(String locaFileName,String remoteFileName) throws Exception
	{
		FTPClient ftpClient = new FTPClient(); 
        FileOutputStream fos = null; 
    	boolean isSuccessed = false;
    	locaFileName = JBusConfig.FTP_TEMP+locaFileName;
    	remoteFileName =JBusConfig.FTP_PATH+remoteFileName;
        try { 
        	ftpClient.connect(JBusConfig.FTP_IP); 
        	isSuccessed = ftpClient.login(JBusConfig.FTP_USER,JBusConfig.FTP_PWD); 
        	System.out.println("isSuccessed=="+isSuccessed);
         	File oldFile = new File(locaFileName);
 	        fos = new FileOutputStream(locaFileName); 
            ftpClient.setBufferSize(1024); 
            //设置文件类型（二进制） 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            System.out.println("ftpClient.getLocalAddress()="+ftpClient.getControlEncoding());
            isSuccessed = ftpClient.retrieveFile(remoteFileName, fos);
             System.out.println("isSuccessed=="+isSuccessed);
         } catch (IOException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("FTP客户端出错！", e); 
        } finally { 
            IOUtils.closeQuietly(fos); 
            try { 
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("关闭FTP连接发生异常！", e); 
            } 
        } 
	
 
		return isSuccessed;
	}
	
	// 计算文件的 MD5 值
	public  static String getFileMD5(File file) {
	    if (!file.isFile()) {
	        return null;
	    }
	    MessageDigest digest = null;
	    FileInputStream in = null;
	    byte buffer[] = new byte[8192];
	    int len;
	    try {
	        digest =MessageDigest.getInstance("MD5");
	        in = new FileInputStream(file);
	        while ((len = in.read(buffer)) != -1) {
	            digest.update(buffer, 0, len);
	        }
	        BigInteger bigInt = new BigInteger(1, digest.digest());
	        return bigInt.toString(16);
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    } finally {
	        try {
	            in.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}
	 
	
	/**
	 * 通过sftp方式下载文件
	 * 
	 * @param FtpFileName
	 *          ftp文件名称
	 * @param LocaFileName
	 *          目的文件名称
	 * @return boolean true表示下载文件成功，false表示下载文件失败
	 * @throws Exception
	 */
	public static boolean sftpDownFile(String locaFileName,String remoteFileName) throws Exception
	{
		FileOutputStream fos = null; 
    	boolean isSuccessed = false;
		JSch jsch = new JSch(); // 创建JSch对象
		try {
			// 根据用户名，主机ip，端口获取一个Session对象
		/*	session = jsch.getSession(Properties.getString("FTP_USER"), 
					Properties.getString("FTP_IP"), Integer.valueOf(Properties.getString("FTP_PORT")));
			String password = Properties.getString("FTP_PWD");
			if(StringUtil.isNotEmpty(password))
			{
				//设置密码
				session.setPassword(password);
			}
			
			java.util.Properties config = new java.util.Properties();
	        config.put("StrictHostKeyChecking", "no");
	        session.setConfig(config); // 为Session对象设置properties
	        String ftp_timeout = Properties.getString("FTP_TIMEOUT");
	        if(StringUtil.isEmpty(ftp_timeout))
	        {
	        	ftp_timeout = "30000";
	        }
	        session.setTimeout(Integer.valueOf(ftp_timeout)); // 设置timeout时间
	        session.connect(); // 通过Session建立链接
	        
	        Channel channel = session.openChannel("sftp");// 打开SFTP通道
            channel.connect();  //建立SFTP通道的连接
            sftp = (ChannelSftp) channel;  
            
            
            locaFileName = Properties.getString("FTP_TEMP")+locaFileName;
        	remoteFileName = Properties.getString("FTP_PATH")+remoteFileName;
            //文件存在性判断
            File oldFile = new File(locaFileName);
            File remoteFile = new File(remoteFileName);
            if(oldFile.exists()){
 	        	fos = new FileOutputStream(locaFileName.substring(0,locaFileName.length()-4)+"TMP"+".pdf");
	            sftp.cd(remoteFile.getParentFile().getAbsolutePath());
	            sftp.get(remoteFileName, fos);  
	            String newFilePath = locaFileName.substring(0,locaFileName.length()-4)+"TMP"+".pdf";
	            File newfile = new File(newFilePath);
	            if(getFileMD5(oldFile).equals(getFileMD5(newfile))){
	            	newfile.delete();
	            	isSuccessed = false;
	            }else{
	            	oldFile.delete();
	            	newfile.renameTo(new File(locaFileName));
	            	isSuccessed = true;
	            }
	        }else{
	        	oldFile.getParentFile().mkdirs();
	        	fos = new FileOutputStream(locaFileName); 
	        	sftp.cd(remoteFile.getParentFile().getAbsolutePath()); 
	            sftp.get(remoteFileName, fos);
	            isSuccessed = true;
	        }
            */
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			throw new RuntimeException("SFTP客户端出错！", e); 
		} 
		finally
		{
			IOUtils.closeQuietly(fos); 
			if (sftp != null) {
				sftp.disconnect();
	        }
	        if (session != null) {
	            session.disconnect();
	        }
		}
        
		return isSuccessed;
	}
	
//	public static void main(String[] args) {
//		try {
//			FtpTool.sftpUpload(new File("D:\\apache-tomcat-7.0.70\\webapps\\directManager\\upload\\20160701\\19year_banner.jpg"), "/home/tomcat/pdfFile", "123456.jpg");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	public static void main(String[] args) { 
	 	//ftpUpload("/Users/macbook/Desktop/directBank_20160413.tar","/upload","ftpTest.tar"); 
		try {
			doDownFile("1.txt","license.txt");
		} catch (Exception e) {
			e.printStackTrace();
		} 
	} 
}  
